﻿using System;
using System.Threading.Tasks;
using Castle.DynamicProxy;
using NLog;

namespace Apps.Extensions.Logger
{
    public class LoggingInterceptor : IInterceptor
    {
        private static readonly ILogger logger = LogManager.GetCurrentClassLogger();

        public void Intercept(IInvocation invocation)
        {
            try
            {
                logger.Info($"调用方法: {invocation.Method.Name} 开始");
                invocation.Proceed();
                if (invocation.Method.ReturnType == typeof(Task))
                {
                    ((Task)invocation.ReturnValue).ContinueWith(task =>
                    {
                        if (task.IsFaulted)
                        {
                            logger.Error(task.Exception, $"调用方法: {invocation.Method.Name} 发生异常");
                        }
                        else
                        {
                            logger.Info($"调用方法: {invocation.Method.Name} 完成");
                        }
                    });
                }
                else
                {
                    logger.Info($"调用方法: {invocation.Method.Name} 完成");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"调用方法: {invocation.Method.Name} 发生异常");
                throw;
            }
        }
    }
}
